<?php

namespace plugin\coupon\event;

use plugin\coupon\app\model\Coupon;
use plugin\coupon\app\model\CouponReceiveLog;
use support\Db;

class Cancel
{
    public function handle($param)
    {
        $receivedCouponModel = new CouponReceiveLog();
        $usedCoupon = $receivedCouponModel->getInfoByWhere([
            'order_id' => $param['order_id'],
        ], ['id','coupon_id','end_time']);

        if (!empty($usedCoupon)) {
            $receivedCouponModel->updateById([
                'order_id' => 0,
                'status' => (now() > $usedCoupon['end_time']) ? 3 : 1,
                'update_time' => now()
            ], $usedCoupon['id']);

            // 减少对应的使用
            Db::beginTransaction();
            try {

                $couponModel = new Coupon();
                $couponModel->where('id', $usedCoupon['coupon_id'])->lock(true)->first();
                $couponModel->where('id', $usedCoupon['coupon_id'])->decrement('used_num', 1);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }
        }
    }
}
